import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import compression from 'vite-plugin-compression'
import legacy from '@vitejs/plugin-legacy'
import autoprefixer from 'autoprefixer'
import { nodePolyfills } from 'vite-plugin-node-polyfills'

// https://vitejs.dev/config/
export default ({ mode }: { mode: string }) => {
  const env = loadEnv(mode, process.cwd())

  return defineConfig({
    base: './',
    plugins: [
      vue(),
      vueJsx(),
      legacy({
        targets: ['defaults', 'not IE 11']
      }),
      compression({
        threshold: 1024 * 5
      }),
      nodePolyfills()
    ],
    esbuild: {
      drop: env.VITE_USER_NODE_ENV === 'production' ? ['console', 'debugger'] : []
    },
    css: {
      postcss: {
        plugins: [
          autoprefixer({
            overrideBrowserslist: ['Android 4.1', 'iOS 7.1', 'Chrome > 40', 'ff > 31', 'ie > 11'],
            grid: true
          })
        ]
      }
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      open: true,
      host: '0.0.0.0',
      port: 5985,
      proxy: {
        '^/api': {
          target: env.VITE_BASE_URL,
          changeOrigin: true
        }
      }
    },
    build: {
      target: ['es2015', 'chrome63'],
      cssTarget: ['chrome63'],
      rollupOptions: {
        output: {
          chunkFileNames: 'js/[name]-[hash].js', // 引入文件名的名称
          entryFileNames: 'js/[name]-[hash].js', // 包的入口文件名称
          assetFileNames: '[ext]/[name]-[hash].[ext]', // 资源文件像 字体，图片等\
          manualChunks: {
            vue: ['vue', 'vue-router', 'vue-i18n'],
            pinia: ['pinia', 'pinia-plugin-persistedstate'],
            highlight: ['highlight.js', '@highlightjs/vue-plugin'],
            pdf: ['pdfjs-dist'],
            word: ['docx-preview'],
            xlsx: ['xlsx']
          }
        }
      }
    }
  })
}
